package com.wolfking.converter.transform.extend;

import com.wolfking.converter.transform.AbstractExtendTransform;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

@Slf4j
public class CostTimeSecondTransform extends AbstractExtendTransform<Object> {

    @Override
    public Object transform(Object value) throws Exception {
        if (Objects.isNull(value)) {
            return "";
        }
        if (value instanceof String && StringUtils.isBlank(value.toString())) {
            return value;
        }
        try {
            int s = Integer.parseInt(value.toString());
            int day = s / 86400;
            int hour = (s % 86400) / 3600;
            int minute = (s % 3600) / 60;
            int second = s % 60;
            if (day > 0) {
                StringBuilder sb = new StringBuilder();
                sb.append(day).append("天");
                if (day < 5 && hour > 0) {
                    sb.append(hour).append("小时");
                }
                return sb.toString();
            }
            if (hour > 0) {
                StringBuilder sb = new StringBuilder();
                sb.append(hour).append("小时");
                if (minute > 0) {
                    sb.append(minute).append("分");
                }
                return sb.toString();
            }
            if (minute > 0) {
                if (minute >= 10) {
                    return minute + "分";
                } else if (minute >= 5) {
                    if (second > 0) {
                        return minute + "分" + second + "秒";
                    } else {
                        return minute + "分";
                    }
                } else {
                    return (minute * 60 + second) + "秒";
                }
            }
            if (second == 0) {
                return "小于1秒";
            }
            return second + "秒";
        } catch (Exception e) {
            log.warn("", e);
            return value;
        }
    }
}
